package com.mdinfo.system.service.impl;

import com.mdinfo.base.common.bean.*;
import com.mdinfo.base.utils.SystemUtil;
import com.mdinfo.base.utils.TimeUtil;
import com.mdinfo.system.bean.SysDept;
import com.mdinfo.system.mapper.SysDeptMapper;
import com.mdinfo.system.param.DeptParam;
import com.mdinfo.system.service.IDeptService;
import com.mdinfo.system.vo.DeptVo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * Created by Administrator on 2017/11/29.
 */
@Service
@Transactional
public class DeptServiceImpl implements IDeptService {

    @Resource
    private SysDeptMapper deptMapper;

    /**
     * 添加部门
     */
    public CommonResult<Void> add(DeptParam.AddParam param){
        SysDept dept = deptMapper.getByShortName(param.getShortName());
        if(dept!=null){
            return Ref.error("该名称已经存在");
        }

        int level = 0;
        //判断上级部门是否存在
        if(param.getPid()!=0){
            SysDept pdept = deptMapper.selectById(param.getPid());
            if(pdept==null){
                return Ref.error("上级部门不存在");
            }
            level = pdept.getLevel() + 1;
        }

        dept = new SysDept();
        dept.setZoom(param.getZoom());
        dept.setLng(param.getLng());
        dept.setLat(param.getLat());
        dept.setFullName(param.getFullName());
        dept.setCreateTime(new Date());
        dept.setMgrName(param.getMgrName());
        dept.setMgrPhone(param.getMgrPhone());
        dept.setShortName(param.getShortName());
        dept.setPid(param.getPid());
        dept.setLocation(param.getLocation());
        dept.setLevel(level);
        deptMapper.insert(dept);
        return Ref.ok();
    }

    /**
     * 修改部门
     */
    public CommonResult<Void> modify(DeptParam.ModifyParam param){

        SysDept dept = deptMapper.selectById(param.getDeptId());
        if(dept==null){
            return Ref.error("错误的部门编号");
        }
        SysDept temp = deptMapper.getByShortNameAndNotId(param.getShortName(), param.getDeptId());
        if(temp!=null){
            return Ref.error("该名称已经存在");
        }

        int level = 0;
        //判断上级部门是否存在
        if(param.getPid()!=0){
            SysDept pdept = deptMapper.selectById(param.getPid());
            if(pdept==null){
                return Ref.error("上级部门不存在");
            }
            level = pdept.getLevel() + 1;
        }


        dept.setPid(param.getPid());
        dept.setShortName(param.getShortName());
        dept.setMgrPhone(param.getMgrPhone());
        dept.setMgrName(param.getMgrName());
        dept.setFullName(param.getFullName());
        dept.setLat(param.getLat());
        dept.setLng(param.getLng());
        dept.setZoom(param.getZoom());
        dept.setLocation(param.getLocation());
        dept.setLevel(level);
        deptMapper.updateById(dept);
        return Ref.ok();
    }

    /**
     * 删除部门
     */
    public CommonResult<Void> delete(DeptParam.DeleteParam param){
        SysDept dept = deptMapper.selectById(param.getDeptId());
        if(dept==null){
            return Ref.error("错误的部门编号");
        }
        List<SysDept> children = deptMapper.getByPid(dept.getId());
        if(children.size()>0){
            return Ref.error("该部门有子部门,不能删除");
        }
        deptMapper.deleteById(dept.getId());
        return Ref.ok();
    }

    /**
     * 获取部门列表(本部门及下属部门)
     */
    public CommonResult<DataGrid<DeptVo.ListOwnVo>> listOwn(DeptParam.ListOwnParam param){

        /**
         * 获取redis中保存的用户部门id.直接通过数据库查询出下级部门树
         */
        MemberInfo info = SystemUtil.getInfo();
        List<SysDept> depts = deptMapper.listTreeCurrent(info.getDeptId());

        //模糊查询
        List<SysDept> collect = depts.stream()
                //条件过滤,判断全称和简称是否包含指定字符串
                .filter(dept -> {
                    if (StringUtils.isNotEmpty(param.getKey())) {
                        return dept.getFullName().contains(param.getKey()) ||
                                dept.getShortName().contains(param.getKey());
                    } else {
                        return true;
                    }
                })
                .collect(Collectors.toList());
        //总数
        int count = collect.size();
        //分页数据
        List<DeptVo.ListOwnVo> vos = collect.stream()
                .filter(dept ->{
                    if(StringUtils.isNotEmpty(param.getKey())){
                        return dept.getFullName().contains(param.getKey()) ||
                                dept.getShortName().contains(param.getKey());
                    }else{
                        return true;
                    }
                })
                .map(dept->{
                    DeptVo.ListOwnVo vo = new DeptVo.ListOwnVo();
                    vo.setCreateTime(TimeUtil.formater(dept.getCreateTime()));
                    vo.setDeptId(dept.getId());
                    vo.setFullName(dept.getFullName());
                    vo.setLat(dept.getLat());
                    vo.setLng(dept.getLng());
                    vo.setMgrName(dept.getMgrName());
                    vo.setMgrPhone(dept.getMgrPhone());
                    vo.setShortName(dept.getShortName());
                    vo.setPid(dept.getPid());
                    vo.setZoom(dept.getZoom());
                    vo.setLocation(dept.getLocation());
                    SysDept pdept = deptMapper.selectById(dept.getPid());
                    if(pdept!=null){
                        vo.setPname(pdept.getShortName());
                    }
                    return vo;

                })
                .skip(param.getStart())
                .limit(param.getNum())
                .collect(Collectors.toList());
        DataGrid<DeptVo.ListOwnVo> dataGrid = new DataGrid<>();
        dataGrid.setRows(vos);
        dataGrid.setTotal(count);
        return Ref.ok(dataGrid);

        /*
            之前的版本,获取所有部门进行过滤

        List<SysDept> depts = deptMapper.listAll();
        MemberInfo info = SystemUtil.getInfo();



        List<SysDept> collect = depts.stream()
            //条件过滤,判断全称和简称是否包含指定字符串
            .filter(dept -> {
                if (StringUtils.isNotEmpty(param.getKey())) {
                    return dept.getFullName().contains(param.getKey()) ||
                            dept.getShortName().contains(param.getKey());
                } else {
                    return true;
                }
            })
            //部门过滤,选择只属于自己管辖的部门
            .filter(dept->{
                boolean temp = false;
                for(Integer id : info.getDeptIdList()){
                    if(id.intValue()==dept.getId().intValue()){
                        temp = true;
                        break;
                    }
                }
                return temp;
            })
            .collect(Collectors.toList());
        //总数
        int count = collect.size();
        //分页数据
        List<DeptVo.ListOwnVo> vos = collect.stream()
            .filter(dept ->{
                if(StringUtils.isNotEmpty(param.getKey())){
                    return dept.getFullName().contains(param.getKey()) ||
                            dept.getShortName().contains(param.getKey());
                }else{
                    return true;
                }
            })
            .map(dept->{
                DeptVo.ListOwnVo vo = new DeptVo.ListOwnVo();
                vo.setCreateTime(TimeUtil.formater(dept.getCreateTime()));
                vo.setDeptId(dept.getId());
                vo.setFullName(dept.getFullName());
                vo.setLat(dept.getLat());
                vo.setLng(dept.getLng());
                vo.setMgrName(dept.getMgrName());
                vo.setMgrPhone(dept.getMgrPhone());
                vo.setShortName(dept.getShortName());
                vo.setPid(dept.getPid());
                vo.setZoom(dept.getZoom());
                vo.setLocation(dept.getLocation());
                SysDept pdept = deptMapper.selectById(dept.getPid());
                if(pdept!=null){
                    vo.setPname(pdept.getShortName());
                }
                return vo;

            })
            .skip(param.getStart())
            .limit(param.getNum())
            .collect(Collectors.toList());
        DataGrid<DeptVo.ListOwnVo> dataGrid = new DataGrid<>();
        dataGrid.setRows(vos);
        dataGrid.setTotal(count);
        return Ref.ok(dataGrid);*/
    }

    /**
     * 获取部门树(本部门及下属部门)
     */
    public CommonResult<List<DeptVo.ListTreeOwnVo>> listTreeOwn(){


        /**
         * 获取redis中保存的用户部门id.直接通过数据库查询出下级部门树
         */
        MemberInfo info = SystemUtil.getInfo();
        List<SysDept> depts = deptMapper.listTreeCurrent(info.getDeptId());
        List<DeptVo.ListTreeOwnVo> vos = depts.stream()
                .map(dept->{
                    DeptVo.ListTreeOwnVo vo = new DeptVo.ListTreeOwnVo();
                    vo.setDeptId(dept.getId());
                    vo.setName(dept.getShortName());
                    vo.setPid(dept.getPid());
                    return vo;
                }).collect(Collectors.toList());
        return Ref.ok(vos);

        /*
        之前的版本,获取所有的部门.然后过滤

        List<SysDept> depts = deptMapper.listAll();
        MemberInfo info = SystemUtil.getInfo();
        List<DeptVo.ListTreeOwnVo> vos = depts.stream()
                //部门过滤,选择只属于自己管辖的部门
            .filter(dept->{
                boolean temp = false;
                for(Integer id : info.getDeptIdList()){
                    if(id.intValue()==dept.getId().intValue()){
                        temp = true;
                        break;
                    }
                }
                return temp;
            })
            .map(dept->{
                DeptVo.ListTreeOwnVo vo = new DeptVo.ListTreeOwnVo();
                vo.setDeptId(dept.getId());
                vo.setName(dept.getShortName());
                vo.setPid(dept.getPid());
                return vo;
            }).collect(Collectors.toList());
        return Ref.ok(vos);*/
    }

    /**
     * 获取当前用户可用的部门id集合
     */
    public List<Integer> myDeptIdList(int deptId){

//        Tree<SysDept> tree = createTree();
//        Tree<SysDept> myTree = Tree.getMyTree(tree, deptId);
//        List<Integer> listMyId = Tree.listMyId(myTree, null);
//        return listMyId;
//
        List<SysDept> depts = deptMapper.listTreeCurrent(deptId);
        return depts.stream()
                .map(dept->dept.getId())
                .collect(Collectors.toList());
    }


    /**
     * 获取所有部门的部门树结构
     */
    private Tree<SysDept> createTree(){

        List<SysDept> depts = deptMapper.listAll();
        List<Tree<SysDept>> trees = depts.stream().map(dept->{
            Tree<SysDept> tree = new Tree<>();
            tree.setId(dept.getId());
            tree.setPid(dept.getPid());
            tree.setName(dept.getShortName());
            tree.setData(dept);
            return tree;
        }).collect(Collectors.toList());

        List<Tree<SysDept>> treeList = Tree.createTree(trees, 0);
        if(treeList.size()==1){
            return treeList.get(0);
        }
        return null;
    }
}
